package com.base;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ImageCodeServlet extends HttpServlet {
	static final long serialVersionUID = 11092306L;
	private static final String CONTENT_TYPE = "image/gif";
	int fontSize;
	int imgHeight;
	int imgWidth;

	public ImageCodeServlet() {
		this.imgWidth = 100;
		this.imgHeight = 20;
		this.fontSize = 12;
	}

	public void destroy() {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String authCode = (String) session.getAttribute("auth-code");
		if (authCode == null)
			authCode = "?";
		String sWidth = request.getParameter("w");
		try {
			this.imgWidth = Integer.parseInt(sWidth);
		} catch (Exception e) {
			this.imgWidth = 100;
		}
		ServletOutputStream out = response.getOutputStream();
		try {
			response.setContentType(CONTENT_TYPE);
			byte[] gif = drawString(authCode);
			response.setContentLength(gif.length);
			out.write(gif, 0, gif.length);
			out.flush();
			out.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private byte[] drawString(String text) {
		BufferedImage bufferImgage = new BufferedImage(this.imgWidth,
				this.imgHeight, 1);

		Graphics2D g2d = bufferImgage.createGraphics();

		if (text.length() <= 8)
			this.fontSize = 18;
		else if (text.length() <= 10)
			this.fontSize = 16;
		else if (text.length() <= 12)
			this.fontSize = 14;
		else {
			this.fontSize = 12;
		}

		Font font = new Font("Lucida Handwriting", 1, this.fontSize);
		FontMetrics fm = g2d.getFontMetrics(font);
		int textWidth = fm.stringWidth(text);
		int textHeight = fm.getAscent();

		int x = (this.imgWidth - textWidth) / 2;
		int y = (this.imgHeight + textHeight) / 2 - fm.getDescent() + 1;

		g2d.setBackground(new Color(140, 240, 200));
		g2d.fillRect(0, 0, this.imgWidth, this.imgHeight);
		g2d.setColor(new Color(140, 240, 60));
		g2d.setFont(font);
		g2d.drawString(text, x, y);
		g2d.dispose();
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufferImgage, "jpg", bout);
		} catch (IOException ex) {
		}
		return bout.toByteArray();
	}

	public void init() throws ServletException {
	}

}
